package test
{
	import com.trg.flex.remote.RemoteCall;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	public class TestCall extends RemoteCall
	{
		public function TestCall(latency:int = 0, range:int = 0, errorProbability:Number = 0) {
			this.latency = latency;
			this.range = range;
			this.errorProbability = errorProbability;
		}
		
		public var errorProbability:Number;
		public var latency:int = 0;
		public var range:int = 0;
		
		private var callback:Function;
		private var outcome:String;
		
		public static var connected:Boolean = true;
		public static var authenticated:Boolean = true;
		
		[Bindable]
		public var going:Boolean;
			
		override public function fire(callback:Function):void {
			this.callback = callback;

            if (latency > 0) {
				var myTimer:Timer = new Timer(latency + Math.random() * range * 2 - range, 1);
	            myTimer.addEventListener("timer", timerHandler);
            	myTimer.start();
            }
            	
            dispatchEvent(new Event("hitServer"));
            going = true;
		}
		
		override public function applyOutcome():void {
			if (outcome == OUTCOME_RESULT) {
				applyResult(new ResultEvent(ResultEvent.RESULT, false, true, outcome));
			} else {
				applyFault(new FaultEvent(FaultEvent.FAULT, false, true, new Fault("something bad happened", outcome)));
			}
		}
		
		private function timerHandler(event:TimerEvent):void {
            finish();
        }
        
        public function finish(outcome:String = null):String {
        	going = false;
    		if (!connected) {
    			outcome = OUTCOME_CONNECTION_FAULT;
    		} else if (!authenticated) {
    			outcome = OUTCOME_AUTHENTICATION_FAULT;
    		} else if (Math.random() < errorProbability) {
            	outcome = OUTCOME_FAULT;
            } else {
            	outcome = OUTCOME_RESULT;
            }
        	this.outcome = outcome;
        	callback(this, outcome);
        	return outcome;
        }
		
	}
}